<template>
  <div class="message">
    <SwipePagination v-model="page" :can-swipe-left="false">
      <HeadContainer class="conversation bg-background" :title="$t('nav.message')" disable-back>
        <!-- 系統通知 -->
        <Column
          class="system-notify"
          system
          :nickname="$t('title.fantasiSystemNotify')"
          :username="'fantasi_official'"
          :content="firstNotifyContent"
          :unread-count="notifyUnreadCount"
          :timestamp="firstNotifyDate"
          @click="userClick(SYSTEM_NOTIFY_ID)"
        ></Column>
        <!-- 私人訊息 -->
        <div v-if="userList?.length !== 0" class="user-list">
          <Column
            v-for="user in userList"
            class="user"
            divider
            :key="user.id"
            :avatar-url="user.avatar"
            :nickname="user.nickname"
            :username="user.username"
            :content="
              user.messages.length === 0
                ? ''
                : user.messages[user.messages.length - 1].contentType === 'photos'
                ? $t('message.imageSended')
                : user.messages[user.messages.length - 1].content
            "
            :unread-count="user.messages.filter((m) => m.unread).length"
            :timestamp="user.messages[user.messages.length - 1]?.timestamp"
            :vip="user.isVip"
            @click="userClick(user.id)"
          ></Column>
        </div>
      </HeadContainer>
      <template #page-2>
        <keep-alive>
          <component
            :is="page2Comp"
            :user-id="conversationId"
            @back="onBack"
            @click:notify="onClickNotify"
            @click:product="onClickProduct"
            @click:creator="onClickCreator"
          ></component>
        </keep-alive>
      </template>
      <template #page-3>
        <FeedPage
          v-if="feedIds || creator"
          :ids="feedIds"
          :creator="creator"
          :active="true"
          :is-notify="isNotify"
          :is-product="!isNotify"
          @back="onBack"
        ></FeedPage>
      </template>
    </SwipePagination>
  </div>
</template>

<script setup>
import { computed, defineAsyncComponent, onActivated, onDeactivated, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useChatStore } from '@/store/chat'
import { useNavStore } from '@/store/nav'
import { useSystemNotifyStore } from '@/store/system-notify'
import { $t } from '@/i18n'
import asyncCompWithLoading from '@/utils/async-comp-with-loading'
import { toDate } from '@/utils/string-helper'
import { NOTIFY_TYPE } from '@/constant/chat'

const SwipePagination = asyncCompWithLoading(() => import('@/components/swipe/SwipePagination.vue'))
const HeadContainer = defineAsyncComponent(() => import('@/components/layout/HeadContainer.vue'))
const Column = defineAsyncComponent(() => import('./Column.vue'))
const Conversation = defineAsyncComponent(() => import('./Conversation.vue'))
const SysmteNotify = asyncCompWithLoading(() => import('./SystemNotify.vue'))
const FeedPage = asyncCompWithLoading(() => import('./FeedPage.vue'))

const navStore = useNavStore()
const { hide: hideNav, show: showNav } = navStore

const chatStore = useChatStore()
const { usersSortByLatestMessage: userList } = storeToRefs(chatStore)

const systemNotifyStore = useSystemNotifyStore()
const { allList } = storeToRefs(systemNotifyStore)
const { notifyRead } = systemNotifyStore
const firstNotifyContent = computed(() => {
  const data = allList.value[0]
  if (data) {
    return data.type === NOTIFY_TYPE.COMMENT
      ? $t('content.commentNotifyMsg', { content: data.content })
      : data.type === NOTIFY_TYPE.REPLY
      ? $t('content.replyNotifyMsg', { user: `@${data.author?.nickname}`, content: data.comment })
      : '...'
  }
  return $t('content.noNotifyMsg')
})
const notifyUnreadCount = computed(() => allList.value.reduce((a, c) => c.nums + a, 0))
const firstNotifyDate = computed(() => (allList.value[0] ? toDate(allList.value[0].created_at) : undefined))

const SYSTEM_NOTIFY_ID = -999
const page = ref(1)
const conversationId = ref(null)
const feedIds = ref(null)
const creator = ref(null)
const isNotify = ref(false)

const page2Comp = computed(() => (conversationId.value === SYSTEM_NOTIFY_ID ? SysmteNotify : Conversation))

let timeoutId
watch(page, (newPage) => {
  if (newPage === 1) {
    timeoutId = setTimeout(() => (conversationId.value = null), 300)
    showNav()
  }
  if (newPage === 2 && conversationId.value !== SYSTEM_NOTIFY_ID) {
    hideNav()
  }
})
function onBack() {
  page.value === 2 && (page.value = 1)
  page.value === 3 && (page.value = 2)
  feedIds.value && (feedIds.value = null)
  creator.value && (creator.value = null)
}

const route = useRoute()
onActivated(() => {
  if (page.value === 2 && conversationId.value !== SYSTEM_NOTIFY_ID) {
    hideNav()
  }
  const { id } = route.query
  if (id) {
    userClick(parseInt(id))
  }
})

onDeactivated(() => {
  if (page.value === 2 && conversationId.value !== SYSTEM_NOTIFY_ID) {
    showNav()
  }
})

// 登出後重置
const accountStore = useAccountStore()
const { isLogin } = storeToRefs(accountStore)
watch(isLogin, (login) => {
  if (!login) {
    page.value = 1
  }
})

function userClick(id) {
  clearTimeout(timeoutId)
  conversationId.value = id
  page.value = 2
}

function onClickNotify(notify) {
  feedIds.value = `${notify.media_id}`
  isNotify.value = true
  page.value = 3

  notifyRead(notify)
}

function onClickProduct(ids) {
  feedIds.value = ids
  isNotify.value = false
}

function onClickCreator(_creator) {
  console.log(`[DEBUG] Message.onClickCreator:`, creator)
  creator.value = _creator
  isNotify.value = false
  page.value = 3
}
</script>

<style lang="scss" scoped>
.message {
  width: 100%;
  height: 100%;
}
</style>
